<?php
/*******************************************************************************
 *
 *  Controller Name: RepairCrew
 *
 *  Date: 5/3/2012
 *  
 *  Description: Controller for the Incident Response team page
 *               performs error checking on forms and updates the appropriate
 *               table in the database when 'submit' is pressed
 *  
 *  Author: David Jarman
 *  
 *  Todo:
 *     NONE
 *
 *  Modification History:  
 * 
 *   Date         Name
 *  ----------   --------------
 *  2012-04-26   DAVID JARMAN
 *  2012-04-26   DAVID JARMAN
 *  2012-04-26   DAVID JARMAN
 *  2012-04-25   DAVID JARMAN
 *  2012-04-25   DAVID JARMAN
 *  2012-04-25   DAVID JARMAN
 *  2012-04-22   HAYDEN WAISANEN
 *  2012-04-22   DAVID JARMAN
 *  2012-04-17   DAVID JARMAN
 *  2012-05-03   DAVID JARMAN
 * 
 *****************************************************************************/
?>
<?php
class RepairCrew extends CI_Controller {
	
    var $data;  //holds data that is passed to views to be displayed

    //constructor
	public function __construct()
	{
		parent::__construct();
	}

    /************************************************************************
    Function:   index()
    Author:     David Jarman
    Description: This is the default page that is loaded when we access
                 repaircrew.php. It gets the current user, then gets their
                 assigned incidents, then does validation on the select form
                 Once submit has been hit, the user is redirected to the edit
                 form view
    Parameters: (none)
    ************************************************************************/
	public function index( )
	{
        //load helpers, database model, and form_validation library
		$this->load->library('session');
        $this->load->helper('dashboard_helper');
		$this->load->model('Incident_model', 'incident');
		$this->load->library('form_validation');
        $this->load->helper('url');

        //gets the current user so we can show their assigned incidents
		$current_user = $this->session->all_userdata();
        
        //load template
        $data['menu'] = getMenu();
        $this->load->view('headerview',$data);

        //put the assigned incidents into our $data variable
		$data['options'] =$this->incident->getTeamIncidences($current_user['UserID']);
		 
        //finally load the incident select view
		$this->load->view('irtIncidentSelect', $data );

  		$this->form_validation->set_rules('IncidentID', 'IncidentID', 'required');
 		if( $this->form_validation->run() == false )
  		{
     		//Do nothing
  		}
  		else
  		{
            //if there was an incident selected, go to the edit form
     		$IncidentID = $this->input->post('IncidentID', TRUE);
            redirect('repaircrew/IncidentEdit/'.$IncidentID);
  		}
	}

    /************************************************************************
       Function: IncidentEdit
       Author:   David Jarman
       Description: Page that is loaded when an incident has been selected.
                    An edit view is displayed that allows the user to edit 
                    the overall status of the incident.
       Parameters: $IncidentID - the unique incident ID that corresponds to
                   the incident the use wants to edit
     ************************************************************************/
    public function IncidentEdit($IncidentID)
    {
        //load helpers, database model, and template view
        $this->load->helper('dashboard_helper');
        $this->load->model('Incident_model', 'incident');
        $this->load->library('form_validation');
        $this->load->helper('date');
        $data['menu'] = getMenu();
        $this->load->view('headerview', $data);

        //set form validation on the estimate date and on the estimate time
        $this->form_validation->set_rules('EstimateDateInput', 'EstimateDateInput', 'required|callback_datetimecheck');
        $this->form_validation->set_rules('EstimateTimeInput', 'EstimateTimeInput', 'required|callback_datetimecheck');

        if($this->form_validation->run() == false)
        {
            //do nothing
        }
        else
        {
            //This large section here gets the data from the view, forms it into
            //data that the database can understand, does some error checking,
            //then updates the database. This is called once the submit has been hit
            //on the view
            $toUpdate = $this->incident->get( $IncidentID );
            $toUpdate = $toUpdate[0];

            //estimate time till completion
            $estimate_date = $this->input->post('EstimateDateInput');
            $estimate_time = $this->input->post('EstimateTimeInput');
            $estimate_datetime = $estimate_date . ' ' . $estimate_time;
            $estimate_format = "%Y-%m-%d %H:%i:%s";
            $estimate_final = mdate($estimate_format, strtotime($estimate_datetime));
            $toUpdate['ExpectedCompletionDate'] = $estimate_final;

            //status
            $status = $this->input->post("Status_Select");
            $toUpdate['Status'] = $this->status_to_int($status);
            $status = $toUpdate['Status'];

            //work started
            $workstarted_date = $this->input->post('WorkStartedDate');
            $workstarted_time = $this->input->post('WorkStartedTime');
            $workstarted_datetime = $workstarted_date . ' ' . $workstarted_time;
            $workstarted_format = "%Y-%m-%d %H:%i:%s";
            $workstarted_final = mdate($workstarted_format, strtotime($workstarted_datetime));
            if( $workstarted_time == "hh:mm AM/PM" )
            {
                $workstarted_datetime = $workstarted_date;
                $workstarted_final = mdate($workstarted_format, strtotime($workstarted_datetime));
            }
            if( $workstarted_date == "MM/DD/YYYY" || $workstarted_date == "" )
            {
                $workstarted_final = null;
            }
            $toUpdate['WorkStarted'] = $workstarted_final;

            //work ended
            $workended_date = $this->input->post('WorkFinishedDate');
            $workended_time = $this->input->post('WorkFinishedTime');
            $workended_datetime = $workended_date . ' ' . $workended_time;
            $workended_format = "%Y-%m-%d %H:%i:%s";
            $workended_final = mdate($workended_format, strtotime($workended_datetime));
            if( $workended_time == "hh:mm AM/PM" )
            {
                $workended_datetime = $workended_date;
                $workended_final = mdate($workended_format, strtotime($workended_datetime));
            }
            if( $workended_date == "MM/DD/YYYY" || $workended_date == "" )
            {
                $workended_final = null;
                if($toUpdate['Status'] == 3)
                {
                    //can't have resolved status without work ended being set
                    $results = $this->incident->get( $IncidentID );
                    $results = $results[0];
                    $data['IncidentData'] = $results;
                    $this->form_validation->set_rules('WorkFinishedDate', 'WorkFinishedDate', 'callback_invalidate');
                    $this->form_validation->run();
                    $this->load->view('irtIncidentEdit', $data);
                    return;
                }
            }

            $toUpdate['WorkFinished'] = $workended_final;

            //cause
            $cause = $this->input->post('Cause');
            $toUpdate['CauseCode'] = $this->cause_to_int($cause);

            //description
            $toUpdate['IRTeamDescription'] = $this->input->post('IncidentDescription');
            
            //actual call to update the incident
            $this->incident->update($toUpdate);
            
            //if the status has been set to resolved, delete it from the database
            if( $status == 3 )
            {
                $this->incident->delete($toUpdate);
            }

            //go back to select page
            redirect('repaircrew/');
        }

        $results = $this->incident->get( $IncidentID );
        $results = $results[0];
        $data['IncidentData'] = $results;
        $this->load->view('irtIncidentEdit', $data);
    }

    /************************************************************************
       Function:    invalidate()
       Author:      David Jarman
       Description: Forces form validation to fail
       Parameters:  $str - the string that is to be checked
     ************************************************************************/
    public function invalidate($str)
    {
        $this->form_validation->set_message('invalidate', 'Work Finished must have a date-time');
        return false;
    }

    /************************************************************************
       Function:    status_to_int()
       Author:      David Jarman
       Description: Fakes an enumerated type
       Parameters:  $status
     ************************************************************************/
    private function status_to_int($status)
    {
        if($status == "Pending")
        {
            return 1;
        }
        else if($status == "Under Repair")
        {
            return 2;
        }
        else if( $status == "Resolved")
        {
            return 3;
        }

        return 1;
    }

    /************************************************************************
       Function:    cause_to_int
       Author:      David Jarman
       Description: Fakes an enumerated type for cause
       Parameters:  $cause
     ************************************************************************/
    private function cause_to_int($cause)
    {
        if($cause == "Unknown")
        {
            return 1;
        }
        else if($cause == "Weather")
        {
            return 2;
        }
        else if($cause == "Vandalism")
        {
            return 3;
        }
        else if($cause == "Corrosion")
        {
            return 4;
        }
        else if($cause == "Accident")
        {
            return 5;
        }
        else if($cause == "Other")
        {
            return 6;
        }

        return 1;
    }

    /************************************************************************
       Function:    datetimecheck()
       Author:      David Jarman
       Description: function for form_validation that checks to make sure
                    that times are correct
       Parameters:  $str
     ************************************************************************/
    public function datetimecheck($str)
	{
	    if(	strtotime($str) == 0 )
        {
            $this->form_validation->set_message('datetimecheck', 'Must be a valid date');
        }
    }

    /************************************************************************
       Function:    relatedreports()
       Author:      David Jarman
       Description: loads the page for viewing attached reports on an incident
                    so the irteam can see more information on an incident
       Parameters:  $IncidentID
     ************************************************************************/
	public function relatedreports( $IncidentID )
	{
		$this->load->model('Report_model','reports');
        $this->load->helper('dashboard_helper');
		$this->load->library('form_validation');

        $data['menu'] = getMenu();	
        $this->load->view('headerview',$data);
		$data['entries'] = $this->reports->getWithIncidentID($IncidentID);
		$data['title'] = "View Related Reports for Incident " . $IncidentID;
		$this->load->view('irtViewReportsView', $data);
        
	}

    /************************************************************************
       Function:    viewReports()
       Author:      David Jarman
       Description: View a single report in detail from the relatedreports 
                    page
       Parameters:  $ReportID
     ************************************************************************/
    public function viewReport($ReportID)
    {
        //Load header with menu
        $this->load->helper('dashboard_helper');
        $data['menu'] = getMenu();
        $this->load->view('headerview',$data);

        $this->load->model('Report_model','report');
        $reports = $this->report->getWithCustomerInfo("WHERE Report.ReportID = $ReportID");
        $data['Report'] = $reports[0];
        $this->load->view('irtViewReportView',$data);

        //Load the footer
        $this->load->view('footerview',$data);
    }
}
?>
